package com.tgl.scheduler;

import com.tgl.util.FileLockUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.Disposable;
import reactor.core.publisher.Mono;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.channels.FileLock;

/**
 * @author tonggl
 * @date 2024/7/23 10:27
 * @description 每秒发送一个请求
 */
@Component
public class PingScheduler {

    private static final Logger logger = LoggerFactory.getLogger(PingScheduler.class);
    public static final String LOCK_FILE1 = "file1.txt";
    public static final String LOCK_FILE2 = "file2.txt";

    private final WebClient webClient = WebClient.create("http://localhost:8081");

    @Scheduled(fixedRate = 1000)
    public void scheduledTask() {
        FileLock fileLock = null;
        String parameter = "Hello";
        try {
            fileLock = FileLockUtil.getLock(new File(LOCK_FILE1));
            Mono<String> result = null;
            if (fileLock != null) {
                result = sendPing(parameter);
            } else {
                fileLock = FileLockUtil.getLock(new File(LOCK_FILE2));
                if (fileLock != null) {
                    result = sendPing(parameter);
                } else {
                    logger.info("rate limited");
                }
            }
            if (result != null) {
                logger.info("Request sent & Pong Respond: " + result.block());
            }
        } catch (FileNotFoundException e) {
            logger.error(e.getMessage());
        } finally {
            if (fileLock!= null) {
                FileLockUtil.releaseLock(fileLock);
            }
        }


    }

    /**
     * 注册一个异步请求
     * @param parameter
     */
    public Mono<String> sendPing(String parameter) {
        return webClient.get().uri(uriBuilder -> uriBuilder.path("/pong")
                .queryParam("parameter", parameter).build())
                .retrieve()
                .onStatus(HttpStatus::is4xxClientError, clientResponse -> {
                    return Mono.just(new RuntimeException("Pong throttled it"));
                })
                .bodyToMono(String.class)
                .onErrorResume(error -> Mono.just("Error occurred: " + error.getMessage()));

    }
}

